import SparkMD5 from "spark-md5";
export function statusToWords(status) {
  switch (status) {
    case -1:
      return "UnAccepted";
    case 0:
      return "Accepted";
    case 1:
      return "Partial Accepted";
    case 2:
      return "Time Limit Exceeded";
    case 3:
      return "Memory Limit Exceeded";
    case 4:
      return "Runtime Error";
    case 5:
      return "System Error";
    case 6:
      return "Compile Error";
    case 7:
      return "Wrong Answer";
    case 8:
      return "Presentation Error";
    case 9:
      return "Submit Failed";
    case 11:
      return "Submitting";
    case 12:
      return "Compiling";
    case 13:
      return "Judging";
    default:
      return "";
  }
}

export function wordsToStatus(words) {
  switch (words) {
    case "UnAccepted":
      return -1;
    case "Accepted":
      return 0;
    case "Partial Accepted":
      return 1;
    case "Time Limit Exceeded":
      return 2;
    case "Memory Limit Exceeded":
      return 3;
    case "Runtime Error":
      return 4;
    case "System Error":
      return 5;
    case "Compile Error":
      return 6;
    case "Wrong Answer":
      return 7;
    case "Presentation Error":
      return 8;
    case "Submit Failed":
      return 9;
    case "Submitting":
      return 11;
    case "Compiling":
      return 12;
    case "Judging":
      return 13;
    default:
      return 15;
  }
}

export function statusToWords2(status) {
  switch (status) {
    case -1:
      return "UnAccepted";
    case 0:
      return "AC";
    case 1:
      return "Partial Accepted";
    case 2:
      return "TLE";
    case 3:
      return "MLE";
    case 4:
      return "RE";
    case 5:
      return "System Error";
    case 6:
      return "Compile Error";
    case 7:
      return "WA";
    case 8:
      return "PE";
    case 9:
      return "Submit Failed";
    case 11:
      return "Submitting";
    case 12:
      return "Compiling";
    case 13:
      return "Judging";
    default:
      return "";
  }
}

//防抖
export const debounce = (fn, delay, immediate = false) => {
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      timer = null;
      if (!immediate) {
        fn.apply(context, args);
      }
    }, delay);
    if (immediate && !timer) {
      fn.apply(context, args);
    }
  };
};

//节流
export const throttle = (fn, delay, immediate = false) => {
  let valid = true;
  let timer = null;
  return function () {
    let context = this;
    let args = arguments;
    if (!valid) {
      return false;
    }
    valid = false;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      !immediate ? fn.apply(context, args) : null;
      valid = true;
    }, delay)(immediate && !timer)
      ? fn.apply(context, args)
      : null;
  };
};

//md图片路径替换
export function beforeChange(text, next) {
  const BASE_URL = import.meta.env.VITE_APP_URL;
  text = text.replace(
    /!\[(.*?)\]\((grape-file\/.*?\.(jpg|png|gif))\)(\{\{\{.*?\}\}\})?/g,
    (match, alt, path, ext, attrs) => {
      // 拼接新路径
      const newPath = `${BASE_URL}/${path.replace("grape-file", "grape-file")}`;

      // 保留属性和格式
      return `![${alt}](${newPath})${attrs || ""}`;
    }
  );
  next(text);
}

//文件计算hash值
export function calculateFileHash(file, onProgress) {
  return new Promise((resolve) => {
    const spark = new SparkMD5.ArrayBuffer();
    const reader = new FileReader();
    const chunkSize = 2 * 1024 * 1024; // 2MB分片
    const chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;

    reader.onload = (e) => {
      spark.append(e.target.result); // 添加分片数据
      currentChunk++;
      // 通过回调传递进度（可选）
      if (typeof onProgress === "function") {
        onProgress(Math.round((currentChunk / chunks) * 100));
      }

      if (currentChunk < chunks) {
        loadNext();
      } else {
        resolve(spark.end()); // 完成计算
      }
    };

    const loadNext = () => {
      const start = currentChunk * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      reader.readAsArrayBuffer(file.slice(start, end));
    };

    loadNext(); // 开始读取第一个分片
  });
}

//换算文件的大小
export function formatSize(val) {
  if (val === 0) return "0 B";
  let k = 1024;
  let sizes = ["B", "KB", "MB", "GB", "PB", "TB", "EB", "ZB", "YB"],
    i = Math.floor(Math.log(val) / Math.log(k));
  return (val / Math.pow(k, i)).toPrecision(3) + "" + sizes[i];
}
//换算文件的分片数量
export function getFileChunks(
  fileSize, //文件大小
  chunkSize = 10, //分片大小，单位为SizeUnit
  sizeUnit = 1024 * 1024 // 需计算的单位，默认为MB，可根据需要自行定义
) {
  // 将MB转换为字节 (1 MB = 1024 KB = 1024*1024 B)
  const bytesPerChunk = chunkSize * sizeUnit;
  // 计算分片数量并向上取整
  return Math.ceil(fileSize / bytesPerChunk);
}
//生成文件分片
export function generateFileChunks(
  file,
  chunkSize = 10,
  sizeUnit = 1024 * 1024
) {
  if (!file || file.size === 0) return [];

  // 转换为字节
  const bytesPerChunk = chunkSize * sizeUnit;
  const totalChunks = Math.ceil(file.size / bytesPerChunk);

  return Array.from({ length: totalChunks }, (_, index) => {
    const start = index * bytesPerChunk;
    const end = Math.min(start + bytesPerChunk, file.size);
    return file.slice(start, end);
  });
}
//拼接头像地址
export function getAvatarUrl(avatar) {
  if (!avatar) return "";
  const BASE_URL = import.meta.env.VITE_APP_URL;
  return `${BASE_URL}/${avatar}`;
}
//拼接头像地址
export function getFileUrl(url) {
  if (!url) return "";
  const BASE_URL = import.meta.env.VITE_APP_URL;
  return `${BASE_URL}/${url}`;
}
